import axios, { AxiosInstance } from 'axios'
// @ts-ignore
import { Utils } from '@/utils/utils'
// @ts-ignore
import { RequestParams } from '@core/interface'

export class Axios {
  private utils: Utils = new Utils()
  private instance: AxiosInstance
  constructor () {
    this.instance = axios.create({
      baseURL: this.utils.CurrentWebSiteUrl(),
      timeout: 30000
    })
    this.ResponseInterceptor()
    this.RequestInterceptor()
  }

  /**
   * Get 请求
   * 请求参数请参考接口：RequestParams
   * @param params
   */
  public async get (params: RequestParams): Promise<Object> {
    try {
      return await this.instance.get(params.url, { params: params.data })
    } catch (e) {
      return e.message
    }
  }

  /**
   * Post 请求
   * 请求参数请参考接口：RequestParams
   * @param params
   */
  public async post (params: RequestParams): Promise<Object> {
    try {
      return await this.instance.post(params.url, params.data)
    } catch (e) {
      return e.message
    }
  }

  /**
   * Put 请求
   * 请求参数请参考接口：RequestParams
   * @param params
   */
  public async put (params: RequestParams): Promise<Object> {
    try {
      return await this.instance.put(params.url, params.data)
    } catch (e) {
      return e.message
    }
  }

  /**
   * Put 请求
   * 请求参数请参考接口：RequestParams
   * @param params
   */
  public async delete (params: RequestParams): Promise<Object> {
    try {
      return await this.instance.delete(params.url, { params: params.data })
    } catch (e) {
      return e.message
    }
  }

  /**
   * 添加响应拦截器
   * @constructor
   */
  public async ResponseInterceptor (): Promise<any> {
    this.instance.interceptors.response.use(function (response) {
      return response.data
    }, function (error) {
      return Promise.reject(error)
    })
  }

  /**
   * 添加请求拦截器
   * @constructor
   */
  public async RequestInterceptor (): Promise<any> {
    this.instance.interceptors.request.use(function (config) {
      return config
    }, function (error) {
      return Promise.reject(error)
    })
  }
}
